
const Controller = require('egg').Controller
const path = require('path')
const fs = require('fs')
const pump = require('pump')

/**
 * @controller 文件上传 Files
 */
class FilesController extends Controller {
  /**
   * @summary 文件上传
   * @router post /files
   * @request formData file files
   * @consume multipart/form-data
   * @response 200 response<fileRes> OK
   * @Authorization
   */
  async upload() {
    const { ctx } = this

    // 读取表单提交的文件流
    const stream = await ctx.getFileStream()

    // 获取上传的文件名
    const fileName = path.basename(stream.filename)
    const fileType = ctx.helper.getType(fileName)
    // 拼接上传路径
    const filePath = 'app/public/uploads/' + new Date().getTime() + fileType

    // 创建一个可以写入的流
    const writeStream = fs.createWriteStream(filePath)

    // 第一个参数读取流，第二个参数可写流, 上传失败会自动销毁流
    await pump(stream, writeStream)

    ctx.renderBack({ fileInfo: {
      fileName,
      fileType,
      filePath: filePath.replace('app', ''),
      fileSize: stream._readableState.length
    }})
  }
}

module.exports = FilesController
